import { Storage } from "./storage";
import { authApi } from "../api";

const USER_KEY = "user";
const USER_DURATION = 12 * 60 * 60 * 1000; // user有效期
const USER_REFRESH = USER_DURATION / 2; // 在user失效前USER_REFRESH毫秒刷新

export class User {
  static set(value) {
    Storage.set(USER_KEY, value, USER_DURATION);
  }
  static exist() {
    return !!User.get();
  }
  static get() {
    return Storage.get(USER_KEY);
  }
  static remove() {
    Storage.remove(USER_KEY);
  }
  static async refresh() {
    if (Storage.getExpire(USER_KEY) < new Date().getTime() + USER_REFRESH) {
      // 只在user失效前USER_REFRESH毫秒刷新
      this.refreshImmediate();
    }
  }

  static async refreshImmediate() {
    const { code, data } = await authApi.refreshUser();
    if (code !== 1) return;
    User.set(data.user);
  }
}
